<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Minappslists;
use App\Models\Miniappsauthorization;
use App\Models\Minappslistsinfo;
use App\Models\Miniappsauditrestults;
use Illuminate\Support\Facades\Redis;
use App\Services\WechatService;
use App\Services\MiniappopenService;
use App\Services\WechatopenService;
use App\Services\WechatwqopenService;
use EasyWeChat\Factory;
use EasyWeChat\OpenPlatform\Server\Guard;
use Log,Artisan,Auth,Exception,DB,Config;

class WechatController extends Controller
{
    public function wechatBind(Request $request)
    {
        return $request->echostr;
    }
    
    public function authorizationNotice(Request $request)
    {
        $clicent = WechatopenService::openClicent($request);
        if ($clicent["status"] == "error") return "success";
        $message = $clicent["message"];
        Log::info(json_encode($message));
        // 创建试用小程序成功/失败的通知
        if (isset($message["InfoType"])) {
            if ($message["InfoType"] == "notify_third_fastregisterbetaapp") {
                Log::info("notify_third_fastregisterbetaapp------------");
                Log::info(json_encode($message));
                Log::info("notify_third_fastregisterbetaapp------------");
                if ($message["status"] == 0) {
                    $unique_id = $message["info"]->unique_id;
                    // 获取授权方的帐号基本信息
                    $authorizerInfo = MiniappopenService::apiGetAuthorizerInfo($message["AppId"],$message["appid"]);
                    Log::info(json_encode($authorizerInfo));
                    try {
                        $authorizer_info = $authorizerInfo["authorizer_info"];
                        $appid_third = $message["AppId"];
                        $head_img = isset($authorizer_info["head_img"]) ? $authorizer_info["head_img"] : "";
                        $principal_type = ($authorizer_info["principal_name"] == "个人") ? 0 : 1;
                        // 更新小程序授权信息
                        Minappslists::fastRegisterAuth($unique_id,$authorizer_info["nick_name"],$appid_third,$message["appid"],$head_img,$authorizer_info["user_name"],$authorizer_info["qrcode_url"],$principal_type,3);
                    } catch (Exception $e) {
                        Log::info("authorizationNotice----");
                        Log::info($e);
                        Log::info("authorizationNotice----");
                    }
                }
            } elseif ($message["InfoType"] == "notify_third_fastverifybetaapp") {
                if ($message["status"] == 0) {
                    Minappslists::fastVerify($message["appid"],4,$message["status"]);
                } else {
                    Minappslists::fastVerify($message["appid"],4,$message["status"]);
                }
            } elseif ($message["InfoType"] == "authorized" || $message["InfoType"] == "unauthorized" || $message["InfoType"] == "updateauthorized") {
                if ($message["InfoType"] == "authorized") {
                    $authorizer_appid = $message["AuthorizerAppid"];
                    $miniappAuthor = Miniappsauthorization::getOpenTokenDetial($authorizer_appid);
                    if (empty($miniappAuthor)) {
                        // 直接回调里面会处理,无需异步处理
                        $Info = MiniappopenService::apiQueryAuth($message["AppId"],$message["AuthorizationCode"]);
                        // 授权成功
                        Miniappsauthorization::insertOpenToken($message["AppId"],$message["AuthorizerAppid"],$message["AuthorizationCode"],$message["AuthorizationCodeExpiredTime"],$message["PreAuthCode"],1,$message["CreateTime"],$Info["authorization_info"]["authorizer_access_token"],$Info["authorization_info"]["expires_in"],$Info["authorization_info"]["authorizer_refresh_token"],1);
                    }
                } elseif ($message["InfoType"] == "unauthorized") {
                    // 取消认证
                    Miniappsauthorization::updateOpenTokenStatus($message["AuthorizerAppid"],2);
                } else {
                    // 更新授权
                    Miniappsauthorization::updateOpenToken($message["AuthorizerAppid"],$message["AppId"],$message["AuthorizationCode"],$message["AuthorizationCodeExpiredTime"],$message["PreAuthCode"],3);
                }
            } elseif ($message["InfoType"] == "notify_third_fasteregister") {
                // 快速注册企业小程序 - 注册审核事件推送
                $code = $message["info"]->code;
                $component_appid = $message["AppId"];
                $legalPersonaWechat = $message["info"]->legal_persona_wechat;
                $miniInfo = Minappslistsinfo::getMinappsListsInfoByCode($code,$legalPersonaWechat);
                if ($message["status"] == 0) {
                    // 获取授权方的帐号基本信息
                    $authorizerInfo = MiniappopenService::apiGetAuthorizerInfo($component_appid,$message["appid"]);
                    // 更新小程序信息
                    Minappslists::minappsListsFasteRegister($miniInfo->minapps_lists_id,$message["AppId"],$message["appid"],$authorizerInfo["authorizer_info"]["user_name"],$authorizerInfo["authorizer_info"]["qrcode_url"],5);

                    // 更新小程序详细信息
                    Minappslistsinfo::notifyThirdFasteRegister($miniInfo->id,$message["appid"],$authorizerInfo["authorizer_info"]["user_name"]);
                } else {
                    // 根据信息查询最后一次绑定
                    if (empty($miniInfo)) return 'success';
                    // 更新上架状态
                    Minappslists::updateStatusCode($miniInfo->minapps_lists_id,$message["AppId"],"",$message["status"]);
                }
            }
        }
        if (isset($message["Event"])) {
            // 代码审核结果推送
            if ($message["Event"] == "weapp_audit_success" || $message["Event"] == "weapp_audit_fail" || $message["Event"] == "weapp_audit_delay") {
                if ($message["Event"] == "weapp_audit_success") {
                    $status = 8;
                    $restult_status = 1;
                    $reason = "";
                    $screenshot = "";
                    // 获取小程序发布方式
                    $minappsListsInfo = Minappslistsinfo::getMinappsListsByOriginalId($message["ToUserName"]);
                    $miniDetial = Minappslists::getMiniListsListsById($minappsListsInfo->minapps_lists_id);
                    // 获取认证授权
                    $miniAccessToken = MiniappopenService::miniappAccessToken($miniDetial->appid_third,$miniDetial->appid);
                    if (!empty($miniDetial)) {
                        // 自动发布小程序
                        MiniappopenService::wxaRelease($miniAccessToken["access_token"]);
                        // 修改应用搜索可见性
                        MiniappopenService::changeWxaSearchStatus($miniAccessToken["access_token"],1);
                    }
                } elseif ($message["Event"] == "weapp_audit_fail") {
                    $status = 7;
                    $restult_status = 2;
                    $reason = $message["Reason"];
                    $screenshot = $message["ScreenShot"];
                } else {
                    $status = 6;
                    $restult_status = 3;
                    $reason = $message["Reason"];
                    $screenshot = "";
                }
                // 保存审核记录
                Miniappsauditrestults::insertAuditRestults($message["ToUserName"],$restult_status,$reason,$screenshot,$message["CreateTime"]);
                Minappslists::minappsListsStatusByOriginalId($message["ToUserName"],$status);
            }
        }
        return 'success';
    }

    public function MiniappopenServices(Request $request)
    {
        Log::info("MiniappopenServices------------");
        Log::info($request->all());
        Log::info("MiniappopenServices------------");
        // 首次绑定验证接口
        if (isset($request->echostr)) return WechatService::servicesFirstSetting($request->signature,$request->timestamp,$request->nonce,$request->echostr);
        // 用户的 OpenID
        $openid = $request->FromUserName;
        
    }

    public function eventReceptionBack(Request $request,$version,$appId)
    {
        $component_appid = empty($request->component_appid) ? "wxeda4d8afd13b7c36" : $request->component_appid;
        $clicent = WechatopenService::openClicent($request);
        if ($clicent["status"] == "error") return "success";
        $message = $clicent["message"];
        Log::info("eventReceptionBack-------");
        Log::info($message);
        Log::info("eventReceptionBack-------");
        // 代码审核结果推送
        if ($message["Event"] == "weapp_audit_success" || $message["Event"] == "weapp_audit_fail" || $message["Event"] == "weapp_audit_delay") {
            if ($message["Event"] == "weapp_audit_success") {
                $status = 8;
            } elseif ($message["Event"] == "weapp_audit_fail") {
                $status = 7;
            } else {
                $status = 6;
            }
            Minappslists::minappsListsStatusByOriginalId($message["ToUserName"],$status);
        }
        return 'success';
    }

    public function uploadMiniappMedia(Request $request)
    {
        $media = $request->media;
        $mimetype = $media->getMimeType();
        $filetype = "image";
        if(strpos($mimetype,'image') === false) return response()->json(["status"=>"error","code"=>"1001","msg"=>"请上传正确的图片"]);
        if (empty($media)) return response()->json(["status"=>"error","code"=>"1001","msg"=>"请上传正确的图片"]);
        $realpath = $media->getRealPath();
        $images_name = md5(time().rand(10000,99999)).".jpg";
        $images_path = public_path("uploads/".$images_name);
        // 保存临时文件
        copy($realpath,$images_path);
        $miniappsauthorization = Miniappsauthorization::getOpenTokenDetial($request->appid);
        $mediaInfo = MiniappopenService::mediaUpload($miniappsauthorization->component_appid,$miniappsauthorization->authorizer_appid,$miniappsauthorization->authorizer_refresh_token,$images_path);
        $media_id = isset($mediaInfo["media_id"]) ? $mediaInfo["media_id"] : "";
        // 删除临时文件
        unlink($realpath);
        unlink($images_path);
        return response()->json(["status"=>"success","code"=>"1000","msg"=>"素材上传成功！","media_id"=>$media_id]);
    }

    public function miniAuthorizationNotice(Request $request)
    {
        // 雾泉授权获取urlscheme
        $openPlatform = WechatwqopenService::openPlatform();
        $server = $openPlatform->server;
        return $server->serve();
    }

    public function miniEventReceptionBack(Request $request,$version,$appId)
    {
        $openPlatform = WechatwqopenService::openPlatform();
        $officialAccount = $openPlatform->officialAccount($appId);
        $server = $officialAccount->server;
        $server->push(function($message) {
            // 代码审核结果推送
            if ($message["Event"] == "weapp_audit_success" || $message["Event"] == "weapp_audit_fail" || $message["Event"] == "weapp_audit_delay") {
                if ($message["Event"] == "weapp_audit_success") {
                    $status = 8;
                } elseif ($message["Event"] == "weapp_audit_fail") {
                    $status = 7;
                } else {
                    $status = 6;
                }
                Minappslists::minappsListsStatusByOriginalId($message["ToUserName"],$status);
            }
            return 'Welcome!';
        });

        return $server->serve();
    }
}